import '../test.css'
import data from '../data-list'
import React, { useState, useEffect, memo, useCallback } from 'react'
import ListItem from './listItem'
import _ from 'lodash'
import { useGetList } from '../api/index'

const list = data.list

const CommentList = memo(function Comment(props) {
  // const { dataList,setDataList} = useGetList([]);
  const [commentList, setCommentList] = useState(list)
  const [userAddedList, setUserAddedList] = useState([])
  const [sortType, setSortType] = useState('like')
  //监听props.currentData的变化
  useEffect(() => {
    if (props.currentData.comment) {
      setUserAddedList(pre => [...pre, props.currentData])
    }
  }, [props.currentData])

  const deleteItem = useCallback(id => {
    setUserAddedList(pre => pre.filter(item => item.id !== id))
  }, [])

  function showItem(item) {
    props.getItemInfo(item)
  }

  const getSortedList = () => {
    //type
    const { dataList, setDataList } = useGetList()
    const merged = [...dataList, ...userAddedList]
    if (sortType === 'latest') {
      return _.orderBy(merged, 'time', 'desc')
    } else {
      return _.orderBy(merged, 'like', 'desc')
    }
  }
  // 组件挂载时，可以通知父组件调用子组件的方法
  useEffect(() => {
    if (props.onRefReady) {
      props.onRefReady({ orderBy })
    }
  }, [props.onRefReady])

  function orderBy(type) {
    setSortType(type)
  }
  // 子组件 不再使用 forwardRef 和 useImperativeHandle，而是通过 useEffect 在挂载后把方法传给父组件。

  // 父组件 通过 onRefReady 回调接收子组件的方法，并存入 childRef.current。

  // 点击按钮时，父组件通过 childRef.current?.showAlert() 调用子组件的方法。
  const displayList = getSortedList()

  return displayList.map(item => (
    <ListItem
      key={item.id}
      item={item}
      id={props.id}
      deleteItem={deleteItem}
    ></ListItem>
    /* <div className="list-content" style={{margin:'12px'}} key={item.id}>
   <img  src={require(`../images/${item.img}`)} style={{width:'45px',height:'auto'}}  /> <span className="small-letter">{item.name}</span>
    <div style={{fontSize:'14px',fontWeight:600}}>{item.comment}</div>
    <div className="list-bottom small-letter"><span>{item.time}</span><span>点赞数：100</span>
    <button onClick={()=>showItem(item)}>显示</button>
    {props.id === item.id&&<button onClick={()=>deleteItem(props.id)}>删除</button>}</div>
</div> */
  ))
})

export default CommentList
